import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_volcengine_provider/flutter_volcengine_provider.dart';
import '../../common/common.dart';
import '../../common/widgets.dart';

class ErrorTestPage extends StatefulWidget {
  @override
  ErrorTestState createState() => ErrorTestState();
}

class ErrorTestState extends State<ErrorTestPage> with WidgetsBindingObserver {
  bool _iOSReportBackgroundError = false;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (_iOSReportBackgroundError && Platform.isIOS && AppLifecycleState.paused == state) {
      _iOSReportBackgroundError = false;
      generateError();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('异常测试'),
      ),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 8.0, bottom: 8.0),
          children: <Widget>[
            buildButton(context, '触发异常', generateError),
            buildButton(context, '延时3秒触发异常', () => generateErrorDelay(3)),
            buildButton(context, 'iOS后台触发异常', () => _iOSReportBackgroundError = true),
            buildEntryButton(context, '进入白屏页', '/error_test/build_error_page'),
            buildButton(context, '弹出异常对话框', _showErrorDialog),
            buildEntryButton(context, '异常路由信息测试', '/error_test/error_router_test/first_page'),
            buildButton(context, '模拟Native崩溃', () => APMProvider.instance.apmDebug.makeAppCrash()),
            buildButton(context, '模拟Native卡顿', () => APMProvider.instance.apmDebug.makeAppFrozen()),
            buildButton(context, '模拟Native用户异常', () => APMProvider.instance.apmDebug.makeUserException()),
            buildButton(context, '模拟CPU异常', () => APMProvider.instance.apmDebug.makeCPUException()),
            buildButton(context, '模拟内存超出上限', () => APMProvider.instance.apmDebug.makeAppOutOfMemeory()),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _showErrorDialog() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) => buildErrorDialog(context),
    );
  }
}
